package com.huijinhui.wlmtsys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huijinhui.wlmtsys.constant.BehaviorConstants;
import com.huijinhui.wlmtsys.enums.AppHttpCodeEnum;
import com.huijinhui.wlmtsys.mapper.ArticleMapper;
import com.huijinhui.wlmtsys.mess.ArticleVisitStreamMess;
import com.huijinhui.wlmtsys.mess.UpdateArticleMess;
import com.huijinhui.wlmtsys.pojo.dtos.*;
import com.huijinhui.wlmtsys.pojo.entity.ApArticle;
import com.huijinhui.wlmtsys.pojo.entity.User;
import com.huijinhui.wlmtsys.service.ArticleService;
import com.huijinhui.wlmtsys.utils.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getArticleId() == null || checkParam(dto)) {
            // 如果参数为空、文章 ID 为空或参数检查不通过，返回参数无效的错误响应
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            // 如果用户未登录，返回需要登录的错误响应
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        System.out.println(mess);

        // 3. 点赞操作
        if (dto.getOperation() == 0) {
            // 如果操作是点赞（0 表示点赞）
            Object obj = redisTemplate.opsForValue().get((BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString()+user.getId().toString()));
//            Object obj = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (obj!= null) {
                // 如果已经点过赞，返回参数无效的错误响应并提示已点赞
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");

            }
            // 保存当前点赞信息到缓存
            log.info("保存当前key:{},{}, {}", dto.getArticleId(), user.getId(), dto);
            redisTemplate.opsForValue().set((BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString()+user.getId().toString()), JSON.toJSONString(dto));
//            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));
            mess.setAdd(1); // 设置增加的点赞数为 1
        } else {
            // 如果操作是取消点赞
            // 从缓存中删除当前点赞信息
            log.info("删除当前key:{}, {}", dto.getArticleId(), user.getId());
            redisTemplate.delete((BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString()+user.getId().toString()));
//            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            mess.setAdd(-1); // 设置减少的点赞数为 -1
        }
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + mess.getAdd());
        updateById(apArticle);
        // 操作成功，返回成功响应
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 阅读
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            // 如果用户未登录，返回需要登录的错误响应
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        更新阅读次数
        String readBehaviorJson = (String) redisTemplate.opsForValue().get((BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString() + user.getId().toString()));
        if (StringUtils.isNotBlank(readBehaviorJson)){
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBehaviorJson, ReadBehaviorDto.class);
            dto.setCount((short) (readBehaviorDto.getCount()+dto.getCount()));
        }
        redisTemplate.opsForValue().set((BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString() + user.getId().toString()), JSON.toJSONString(dto));

        // 数据聚合
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + mess.getAdd());
        updateById(apArticle);
        // 操作成功，返回成功响应
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            // 如果用户未登录，返回需要登录的错误响应
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 收藏操作
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
        if (dto.getOperation() == 0) {
            // 如果操作是收藏（0 表示收藏）
            Object obj = redisTemplate.opsForValue().get((BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId().toString() + user.getId().toString()));
            if (obj!= null) {
                // 如果已经收藏过，返回参数无效的错误响应并提示已收藏
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
            }
            // 保存当前收藏信息到缓存
            log.info("保存当前key:{},{}, {}", dto.getArticleId(), user.getId(), dto);
            redisTemplate.opsForValue().set((BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId().toString() + user.getId().toString()), JSON.toJSONString(dto));
            mess.setAdd(1); // 设置增加的收藏数为 1

        } else {
            // 如果操作是取消收藏
            // 从缓存中删除当前收藏信息
            log.info("删除当前key:{}, {}", dto.getArticleId(), user.getId());
            redisTemplate.delete((BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId().toString() + user.getId().toString()));
            mess.setAdd(-1); // 设置减少的收藏数为 -1
        }
        // 更新文章收藏数
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + mess.getAdd());
        updateById(apArticle);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}



    private boolean checkParam(LikesBehaviorDto dto) {
        if (dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0) {
            return true;
        }
        return false;
    }

}




